package com.nulldev.util.gui.fontAPI;

import java.io.File;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.io.file.FileUtil;

public class Font {
	private final FontSource source;
	private volatile Object fontRef;
	private volatile java.awt.Font cachedFont;

	public Font(final String fontName) {
		this.source = FontSource.SYSTEM_FONT;
		this.fontRef = fontName;
		this.cachedFont = this.__createFont(16);
	}

	public Font(final File file) {
		this.source = FontSource.FILE_FONT;
		this.fontRef = file;
		this.cachedFont = this.__createFont(16);
	}

	public FontSource getSource() {
		return this.source;
	}

	private java.awt.Font __createFont(final int size) {
		if (fontRef instanceof String) {
			return new java.awt.Font((String) this.fontRef, java.awt.Font.PLAIN, size);
		} else if (fontRef instanceof File) {
			final String ext = FileUtil.getFileExtension((File) fontRef);
			if (ext.equalsIgnoreCase("ttf")) {
				try {
					return java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, (File) this.fontRef);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			} else if (ext.equalsIgnoreCase("otf") && JVM.version() >= 1.7) {
				try {
					return java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, (File) this.fontRef);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	public java.awt.Font getFont() {
		return this.cachedFont;
	}

	public java.awt.Font getFont(final int size) {
		return this.cachedFont.deriveFont((float) size);
	}

	public java.awt.Font getFont(final float size) {
		return this.cachedFont.deriveFont((float) size);
	}
}
